package com.mathslogica.fb;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mathslogica.ML;
import com.mathslogica.MLConstants;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

@SuppressWarnings("serial")
public class FBUserInitServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/plain");
		PrintWriter out = resp.getWriter();

		HttpSession session = req.getSession();
		String authCode = req.getParameter(MLConstants.FB_AUTHCODE);

		String rState = req.getParameter("state");
		String sState = (String) session.getAttribute("state");
		if (rState != null && rState.equalsIgnoreCase(sState)) {
			String tokenUrl = "https://graph.facebook.com/oauth/access_token?client_id="
					+ MLConstants.FB_APP_ID
					+ "&redirect_uri="
					+ MLConstants.REDIRECT_URL
					+ "&client_secret="
					+ MLConstants.FB_APP_SECRET
					+ "&code="
					+ authCode;

			String contents = ML.getUrlContent(tokenUrl);
			System.out.println(contents);

			Map<String, String> param = ML.getParamMap(contents);

			FacebookClient facebookClient = new DefaultFacebookClient(
					param.get(MLConstants.FB_ACCESS_TOKEN));

			User user = facebookClient.fetchObject("me", User.class);

			out.println("User name: " + user.getName());
			out.println("User Id: " + user.getId());

		} else {
			out.println("Fuck off");
		}
		out.close();
	}
}
